import store from '../store'
import tips from '../utils/tips.js'

function getAuth() {
    return new Promise(resolve => {
        uni.getSetting({
            success(res) {
                const authSetting = res.authSetting;
                if(!authSetting['scope.userInfo']) {
                    tips.loaded()
                    uni.navigateTo({
                        url: '/pages/auth/auth'
                    })
                    return false;
                } 
                resolve()
            }
        })
    })
    
}

export default async function onLogin() {
    tips.loading('登录中...')
    await getAuth();
    
    return new Promise((resolve, reject) => {
        // 仅调试使用
        /* if(process.env.NODE_ENV == "development") {
            tips.loaded()
            let account = uni.getStorageSync('account')
            if(account && account.jwt) {
                store.commit('USERINFO', account)
                resolve(account)
                return false;
            }
        } */
        
        uni.login({
            success(res) {
                uni.request({
                    url: `${process.env.VUE_APP_API}/user/login/byApplet`,
                    data: {
                        jsCode: res.code
                    },
                    method: 'post',
                    success(res) {
                        tips.loaded()
                        let {data, statusCode, header} = res;
                        // 用户不存在
                        if(data.code == 1212) {
                            uni.navigateTo({
                                url: '/pages/auth/auth'
                            })
                        } else if(data.code != 0) {
                            tips.toast(data.msg || '登录失败')
                            return false;
                        }
                        if(!header['QS-JWT']) {
                            uni.navigateTo({
                                url: '/pages/auth/auth'
                            })
                            return false;
                        }
                        data.data['jwt'] = header['QS-JWT'];
                        store.commit('USERINFO', data.data)
                        uni.setStorageSync('account', data.data);
                        resolve(data.data);
                    },
                    fail(err) {
                        tips.loaded()
                        if(err && err.errMsg && err.errMsg.indexOf('timeout') ) {
                            tips.toast('登录超时')
                        } else {
                            tips.toast(err.errMsg)
                        }
                    }
                })
            }
        })
    })
    
}
